<template>
    <div>
        <vxe-toolbar ref="toolbarRef" custom :buttons="toolbarButtons" @button-click="buttonClickHandle"></vxe-toolbar>
        <vxe-table :data="tableData" :seq-config="{ startIndex: 0 }" border align="center"
            :column-config="{ resizable: true }" ref="tableRef" :print-config="{}" custom-config="{storage: true}">
            <vxe-column type="seq" title="序号" width="60"></vxe-column>
            <vxe-column field="name" title="姓名"></vxe-column>
            <vxe-column field="sex" title="性别"></vxe-column>
            <vxe-column field="age" title="年龄"></vxe-column>
            <vxe-column field="address" title="地址"></vxe-column>
            <vxe-column field="" title="操作" width="200" fixed="right" show-overflow>
                <template #default="{ row }">
                    <vxe-button status="primary" @click="rowEditHandle(row)">编辑</vxe-button>
                    <vxe-button status="danger" @click="rowRemoveHandle(row)">删除</vxe-button>
                </template>
            </vxe-column>
        </vxe-table>
        <vxe-pager :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            v-model:current-page="tablePage.currentPage" v-model:page-size="tablePage.pageSize" :total="tablePage.total"
            @page-change="handlePageChange">
        </vxe-pager>
        <el-dialog v-model="dialogFormVisible" title="编辑" width="500" @closed="handleDialogClosed">
            <el-form :model="form" :rules="rules" ref="ruleFormRef">
                <el-form-item label="姓名：" prop="name" :label-width="formLabelWidth">
                    <el-input v-model="form.name" autocomplete="off" />
                </el-form-item>
                <el-form-item label="性别：" prop="sex" :label-width="formLabelWidth">
                    <el-select v-model="form.sex" placeholder="请选择....">
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                    </el-select>
                </el-form-item>
                <el-form-item label="年龄：" prop="age" :label-width="formLabelWidth">
                    <el-input v-model.number="form.age" autocomplete="off" />
                </el-form-item>
                <el-form-item label="地址：" prop="address" :label-width="formLabelWidth">
                    <el-input v-model="form.address" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancellationHandle(ruleFormRef)">返回</el-button>
                    <el-button type="primary" @click="saveHandle(ruleFormRef)">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, nextTick, ref, watch } from 'vue';
import { GetAllHero, SaveHeroMessage, DeleteHeroMessage, UpdateHeroMessage } from '@/request/api';
import { pageControlParam } from '@/type';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';

interface RowVO {
    _id: string
    name: string
    sex: string
    age: number
    address: string
    createdAt: string
    updatedAt: string
}
let tableData = ref<RowVO[]>([]);
let isEdit = ref(false);
const ruleFormRef = ref<FormInstance>()
const toolbarButtons = ref([
    { code: 'added', name: '新增', icon: 'vxe-icon-add' },
])
const tableRef = ref()
const toolbarRef = ref()
const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10
})
const dialogFormVisible = ref(false)
const formLabelWidth = '140px';
const form = reactive({
    id: "",
    name: "",
    sex: "",
    age: "",
    address: "",
})
const rules = reactive({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: ["change"] },
    ],
    age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { type: 'number', message: '年龄必须为数字值' }
    ],
    address: [
        { required: true, message: '请输入地址', trigger: 'blur' },
    ],
})
onMounted(() => {
    getAllHero()
})
nextTick(() => {
    // 将表格和工具栏进行关联
    const $table = tableRef.value
    const $toolbar = toolbarRef.value
    if ($table && $toolbar) {
        $table.connect($toolbar)
    }
})
watch(dialogFormVisible, () => {
    if (!dialogFormVisible.value) {
        ruleFormRef.value?.resetFields()
        Object.assign(form, { name: '', age: '', sex: '', address: '' })
    }
})
const handlePageChange = ({ currentPage, pageSize }: pageControlParam) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize;
    getAllHero(currentPage, pageSize)
}
function buttonClickHandle(message: { code: string }) {
    if (message.code == "added") {
        dialogFormVisible.value = true;
    }
}
function rowEditHandle(row: RowVO) {
    isEdit.value = true;
    dialogFormVisible.value = true;
    Object.assign(form, {
        id: row._id,
        name: row.name,
        sex: row.sex,
        age: row.age,
        address: row.address,
    })
}
function rowRemoveHandle(row: RowVO) {
    ElMessageBox.confirm(
        '确定要要删除当前数据?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        DeleteHeroMessage({ id: row._id }).then(res => {
            ElMessage({
                message: res.data.message,
                type: 'success',
            })
            getAllHero(tablePage.currentPage, tablePage.pageSize);
        })
    }).catch(() => {
        console.log("取消删除")
    })
}
async function saveHandle(formEl: FormInstance | undefined) {
    if (!formEl) return
    await formEl.validate(async (valid: boolean, fields: any) => {
        if (valid) {
            try {
                let res;
                if (isEdit.value) {
                    res = await UpdateHeroMessage({ id: form.id, name: form.name, age: form.age, sex: form.sex, address: form.address })
                } else {
                    res = await SaveHeroMessage(JSON.stringify({ name: form.name, age: form.age, sex: form.sex, address: form.address }));
                }
                ElMessage({
                    message: res.data.message,
                    type: 'success',
                })
                dialogFormVisible.value = false;
                getAllHero();
            } catch (error) {
                console.log(error)
            }
        }
    })
}
function cancellationHandle(formEl: FormInstance | undefined) {
    if (!formEl) return
    dialogFormVisible.value = false;
}
function handleDialogClosed() {
    dialogFormVisible.value = false;
}
async function getAllHero(currentPage?: number, pageSize?: number) {
    try {
        const res = await GetAllHero({ page: currentPage, limit: pageSize });
        tableData.value = res.data.data;
        Object.assign(tablePage, { total: res.data.pagination.total, pageSize: res.data.pagination.limit, currentPage: res.data.pagination.currentPage })
    } catch (error) {
        console.log(error)
    }
}
</script>